package com.shen.xiang.test.mybatis;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;

/**
 * 实现了FactoryBean接口
 * 当beanfactory中找不到对象的时候 会从实现了FactoryBean接口的类 调用getobject方法获得对象进行匹配
 *
 */
public class MyMapperFactoryBean<T> implements FactoryBean {
    private Class<T> mapperInterface;
    private SqlSession sqlSession;
    private SqlSessionFactory sqlSessionFactory;

    public SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    /**
     * 自动装配属性 spring会根据sqlSessionFactory类型去容器中找这个对象
     * 如果找不到去factorybean中找
     * 最后sqlSessionFactory在MyBatisFactoryBean中找到
     * @param sqlSessionFactory
     */
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        //获取SqlSession
        this.sqlSession = sqlSessionFactory.openSession();
        this.sqlSessionFactory = (SqlSessionFactory)sqlSessionFactory;
    }

    public MyMapperFactoryBean(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    public Class<T> getMapperInterface() {
        return mapperInterface;
    }

    public void setMapperInterface(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    public SqlSession getSqlSession() {
        return sqlSession;
    }

    //同理 获取mapper代理对象
    @Override
    public Object getObject() throws Exception {
        return sqlSession.getMapper(this.mapperInterface);
    }

    @Override
    public Class<?> getObjectType() {
        return this.mapperInterface;
    }
}
